<template>
  <div :id="id" :class="className" :style="{height:height,width:width}" />
</template>

<script>
import * as echarts from 'echarts'
import resize from './mixins/resize'
import { upFixed, downFixed } from '@/utils'

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: 'chart'
    },
    id: {
      type: String,
      default: 'chart'
    },
    width: {
      type: String,
      default: '200px'
    },
    height: {
      type: String,
      default: '200px'
    },
    data: {
      type: Array,
      default: () => {
        return []
      }
    },
    contrastIndex_obj: {
      type: Object,
      default: () => {
        return {}
      }
    },
    has_dataZoom: {
      type: Boolean,
      default: true
    },
  },
  data() {
    return {
      chart: null,
      xDate: [],
      data_obj: {}
    }
  },
  mounted() {
    this.dataHandle()
  },
  beforeDestroy() {
    if (!this.chart) {
      return
    }
    this.chart.dispose()
    this.chart = null
  },
  methods: {
    dataHandle() {
      this.data_obj = {}
      this.data_obj['组合方案'] = []
      this.data.forEach(item => {
        this.xDate.push(item.networthTime)
        this.data_obj['组合方案'].push(item.networthValue)
      })
      Object.keys(this.contrastIndex_obj).forEach(key => {
        const item = this.contrastIndex_obj[key]
        this.data_obj[key] = item.map(item => item.indexValue) //todo 可能出现日期数据不对应的情况
        // this.data_obj[key] = []
        // item.forEach((e, i) => {
        //   if(e.indexTime == this.xDate[i].networthTime) {
        //     this.data_obj[key].push(e.indexValue)
        //   }else {
        //     this.data_obj[key].push('')
        //   }
        // })
      })
      if(this.chart) this.chart.dispose()
      this.initChart(this.xDate, this.data_obj)
    },
    initChart(xDate, obj) {
      this.chart = echarts.init(document.getElementById(this.id))
      const color_list = ['rgba(225,103,86,1)', 'rgba(129,183,236,1)', 'rgba(238,203,87,1)', 'rgba(173,224,255,1)', 'rgba(255,155,203,1)'] //todo 颜色
      const series = []
      const dataZoom = this.has_dataZoom ? [
        {
          type: 'inside',
          start: 0,
          end: 100
        },{
          realtime: true,
          start: 0, 
          end: 100, 
          xAxisIndex: [0, 100],
          height: '4%',
          bottom: '6%',
          borderColor: '#8FDFFE',
          backgroundColor: '#8fdffe99',
          moveHandleSize: 0, // 上面拖动部分
          dataBackground: {
            areaStyle: {
              color: 'rgba(225,103,86,1)'
            },
            lineStyle: {
              color: 'rgba(225,103,86,1)'
            }
          },
          selectedDataBackground: {
            areaStyle: {
              color: 'rgba(225,103,86,1)'
            },
            lineStyle: {
              color: 'rgba(225,103,86,1)'
            }
          },
          textStyle: {
            fontSize: 11, 
          },
          // 拖拽手柄样式 svg 路径
          handleIcon: 'M512 512m-208 0a6.5 6.5 0 1 0 416 0 6.5 6.5 0 1 0-416 0Z M512 192C335.264 192 192 335.264 192 512c0 176.736 143.264 320 320 320s320-143.264 320-320C832 335.264 688.736 192 512 192zM512 800c-159.072 0-288-128.928-288-288 0-159.072 128.928-288 288-288s288 128.928 288 288C800 671.072 671.072 800 512 800z',
          handleColor: '#8FDFFE',
          handleSize: 14,
          handleStyle: { 
            borderColor: '#8FDFFE', 
            shadowBlur: 4,
            shadowOffsetX: 1,
            shadowOffsetY: 1,
            shadowColor: '#e5e5e5'
          }
        }
      ] : []

      if(Object.keys(obj).length) {
        Object.keys(obj).forEach((key, i) => {
          const item = obj[key]
          series.push({ 
            yAxisIndex: 0,
            name: key,
            type: 'line',   
            symbolSize: 2,
            symbol: 'emptyCircle',
            showSymbol: false,
            lineStyle: {
              width: 1.6
            },
            itemStyle: {
              normal: {
                color: color_list[i],
                borderRadius: 0
              }
            },
            data: item
          })
        })
      }
     
      this.chart.setOption({
        title: {
          text: 'statistics',
          x: '20',
          top: '0',
          textStyle: {
            color: '#fff',
            fontSize: '22'
          },
          subtextStyle: {
            color: '#90979c',
            fontSize: '16'
          }
        },
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            textStyle: {
              color: '#fff'
            } 
          },
          formatter(params) {
            let str = ''
            str += `<div style="padding-bottom: 2px;">${params[0].name}</div>`
            for (let i = 0; i < params.length; i += 1) {
              str += `<div style="display: flex;align-items: center;">
                    ${params[i].marker} 
                    <span style="flex:1;">${params[i].seriesName}</span> 
                    <span style="margin-left: 10px;font-weight: bold;"> ${params[i].data}${(typeof params[i].data)=='number' ? '%' : ''}</span>
                    </div>`
            }
            return str
          }
        },
        grid: {
          left: '7%',
          right: '5%',
          borderWidth: 0,
          textStyle: {
            color: '#fff'
          }
        },
        legend: {
          x: '20%',
          top: '5%',
          textStyle: {
            color: '#90979c'
          },
        },
        calculable: true,
        xAxis: [{
          type: 'category',
          boundaryGap: false, // 折线从x轴起始开始走
          axisLine: {
            lineStyle: {
              color: '#90979c'
            }
          },
          splitLine: {
            show: false
          },
          axisTick: {
            show: true,
            alignWithLabel: true
          },
          splitArea: {
            show: false
          },
          axisLabel: {
            interval: 'auto'
          },
          data: xDate
        }],
        yAxis: [
          {
            type: 'value',
            min: function(value) {
              const num = value.min - (value.max - value.min)/5
              return downFixed(num, 1)
            },
            max: function(value) {
              const num = value.max + (value.max - value.min)/5
              return upFixed(num, 1)
            },
            splitLine: {
              show: true,
              lineStyle: {
                type: 'dashed'
              }
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: '#90979c'
              }
            },
            axisTick: {
              show: true,
              alignWithLabel: true
            },
            axisLabel: {
              interval: 0,
              formatter: function(value) {
                return value.toFixed(4)
              }
            },
            splitArea: {
              show: false
            }
          }, 
          {
            type: 'value',
            min: 'dataMin',
            max: 'dataMax',
            splitLine: {
              show: false,
              lineStyle: {
                type: 'dashed'
              }
            },
            axisLabel: {
              interval: 0,
              formatter: function(value) {
                return value + '%'
              }
            }
          }
        ],
        dataZoom,
        series
      })
      // this.chart.on('datazoom', throttle((params) => {       
      //   const baseline_i = this.chart.getModel().option.dataZoom[0].startValue
      //   const op = this.chart.getOption()
      //   Object.keys(this.data_obj).forEach((key, i) => {
      //     const list = this.data_obj[key]
      //     if(list.length-1 >= baseline_i) {
      //       const baseline_val = this.data_obj[key][baseline_i]
      //       const data = list.map(item => {
      //         if(item != '') {
      //           return (Number(divide(item, baseline_val))+1).toFixed(5)
      //         }else if(item == '') {
      //           return ''
      //         }
      //       })
      //       op.series[i].data = data
      //     }
      //   })
      //   this.chart.setOption(op)
      // }, 500))
    },
  }
}
</script>
